#include "sy_fifo.h"

SY_FIFO_RET sy_fifo_init(sy_fifo_handle* fifo_handle) {
    fifo_handle->H = (sy_fifo_base*)sy_malloc(sizeof(sy_fifo_base));
    if (fifo_handle->H == NULL) {
        return SY_FIFO_INVALID;
    }
    // fifo_handle->L->next = NULL;
    fifo_handle->fifo_number = 0;
    fifo_handle->fifo_lock = false;
    return SY_FIFO_OK;
}

SY_FIFO_RET sy_fifo_push(sy_fifo_handle* fifo_handle, u_int32_t data) {
    sy_fifo_base* temp;
    if ((fifo_handle == NULL) ||(fifo_handle->H == NULL)) {
        return SY_FIFO_INVALID;
    }
    fifo_handle->fifo_lock = true;
    temp = fifo_handle->H;
    while(temp->next != NULL) {
        temp = temp->next;
    }
    temp->next = (sy_fifo_base*)sy_malloc(sizeof(sy_fifo_base));
    if (temp->next == NULL) {
        return SY_FIFO_INVALID;
    }
    temp->next->data = data;
    fifo_handle->L = temp->next;
    fifo_handle->fifo_number += 1;
    fifo_handle->fifo_lock = false;
    return SY_FIFO_OK;
}

SY_FIFO_RET sy_fifo_output(sy_fifo_handle* fifo_handle, u_int32_t* data) {
    sy_fifo_base* temp;
    if (fifo_handle == NULL) {
        return SY_FIFO_INVALID;
    }
    if (fifo_handle->fifo_number <= 0) {
        return SY_FIFO_NULL;
    }
    fifo_handle->fifo_lock = true;
    temp = fifo_handle->H->next;
    *data = temp->data;
    fifo_handle->H->next = temp->next;
    sy_free(temp);
    fifo_handle->fifo_number -= 1;
    fifo_handle->fifo_lock = false;
    return SY_FIFO_OK;
}